package com.rh.realm;

import com.rh.Enums;
import com.rh.entity.Employee;
import com.rh.excrptions.DoException;
import com.rh.service.EmployeeService;
import com.rh.service.RoleService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class EmployeeRealm extends AuthorizingRealm {
    @Autowired
    private EmployeeService employeeService;
    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
       //获取用户名
        String email = principalCollection.getPrimaryPrincipal().toString();
        //根据用户名查询所有
        Employee employeeAllByEmail = employeeService.getEmployeeAllByEmail(email);
        //获取所有用户角色信息
        String roleName = employeeAllByEmail.getRole().getRoleName();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //将角色添加到info中
        info.addRole(roleName);
        return info;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取邮箱
        String email = authenticationToken.getPrincipal().toString();
        System.out.println(email);
        //使用邮箱从数据库中查询数据
        Employee e = employeeService.getEmployeeAllByEmail(email);
        System.out.println(e);
        //判断用户名是否为空
        if(e==null){
            throw new DoException(Enums.AUTHEN_ERROR);
        }
        //设置盐
        ByteSource byteSource=ByteSource.Util.bytes(e.getSalt());
        //将查询出来的用户信息发送到安全管理器
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(e.getEmail(),e.getEmpPassword(),byteSource,getName());
        return info;
    }
}
